package com.foxmail.yusp75.myexam;

/*
Copyright 2017 Yu shanpeng

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.folderselector.FileChooserDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;

import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;


public class SettingActivity extends AppCompatActivity implements FileChooserDialog.FileCallback {

    private TextView txt_file, txt_info;
    private EditText txt_paper;
    private Handler handler;
    private Realm realm;

    private ArrayList<String> list;
    private PaperListAdapter adapter;
    private String path;

    private static int REQUEST_PERMISSION = 10;
    //private static int REQUEST_FILE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        // Handle Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("新增试题");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        // ui
        txt_paper = findViewById(R.id.paper);
        txt_info = findViewById(R.id.import_info);

        txt_file = findViewById(R.id.setting_file);
        txt_file.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {

                    ActivityCompat.requestPermissions(SettingActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
                } else {
                    new FileChooserDialog.Builder(getApplicationContext())
                            .extensionsFilter(".pcm", ".txt")
                            .tag("paper")
                            .show(SettingActivity.this);
                }
            }
        });
        // 题库列表
        ListView listView = findViewById(R.id.list_paper);
        list = new ArrayList<>();
        adapter = new PaperListAdapter(this, listener_del, listener_overview, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String paper_selected = list.get(i);

                RealmQuery query = realm.where(Question.class).equalTo("paper.name",
                        paper_selected);
                long c_item = query.count();
                long c_wrong = query.greaterThan("c_wrong", 0).count();
                long c_bookmark = query.equalTo("bookmark", true).count();

                String info = String.format(Locale.CHINA, "题数：%d，错误数：%d，收藏数：%d",
                        c_item, c_wrong, c_bookmark);
                txt_info.setText(info);
            }
        });

        handler = new Handler();
    }

    @Override
    public void onFileSelection(@NonNull FileChooserDialog dialog, @NonNull File file) {
        path = file.toString();
        String[]  file_name= file.getName().split("\\.");

        txt_file.setText(path);
        txt_paper.setText(file_name[0]);
    }

    @Override
    public void onFileChooserDismissed(@NonNull FileChooserDialog dialog) {

    }

    @Override
    protected void onResume() {
        realm = Realm.getDefaultInstance();
        RealmResults<Paper> papers = realm.where(Paper.class).findAll();
        list.clear();
        for (int i = 0; i < papers.size(); i++)
            list.add(papers.get(i).getName());
        adapter.notifyDataSetChanged();

        super.onResume();
    }

    @Override
    protected void onPause() {
        if (realm != null)
            realm.close();
        super.onPause();
    }


    public void btnImportClick(View view) {
        // 导入
        if (path != null && !path.isEmpty())
            new ImportData(getApplicationContext()).execute(path, txt_paper.getText().toString());
    }

    // 类：导入
    private class ImportData extends AsyncTask<String, Integer, Question> {
        private MaterialDialog dialog;
        private Context context;

        public ImportData(Context context) {
            this.context = context;

        }

        @Override
        protected void onPreExecute() {
            dialog = new MaterialDialog.Builder(SettingActivity.this)
                    .title("导入试题")
                    .content("请稍等。。。")
                    .progress(true, 0)
                    .progressIndeterminateStyle(false).show();

            super.onPreExecute();
        }


        @Override
        protected Question doInBackground(String... values) {

            try {
                InputStream stream = new FileInputStream(values[0]);
                if (values[1].isEmpty()) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "试卷名不能为空", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    MainActivity.data(values[1], stream);
                }

            } catch (FileNotFoundException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "错误：文件未找到。", Toast.LENGTH_LONG).show();
                    }
                });
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            if (dialog != null)
                dialog.dismiss();

            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Question question) {
            dialog.dismiss();
            super.onPostExecute(question);
            // imported
            list.add(txt_paper.getText().toString());
            txt_file.setText("");
            txt_paper.setText("");
            adapter.notifyDataSetChanged();


        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                new FileChooserDialog.Builder(getApplicationContext())
                        .extensionsFilter(".pcm", ".txt")
                        .tag("paper")
                        .show(SettingActivity.this);
            } else {
                finish();
            }
        }
    }

    private View.OnClickListener listener_del = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final int idx = (int) v.getTag();
            final String paper = list.get(idx);
            new MaterialDialog.Builder(SettingActivity.this)
                    .title("提示")
                    .content(String.format("确定删除试题：%s？", paper))
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            //Toast.makeText(getApplicationContext(), "deleted !", Toast.LENGTH_SHORT).show();
                            realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {
                                    realm.where(Paper.class).equalTo("name", paper).findAll().deleteAllFromRealm();
                                    realm.where(Question.class).equalTo("paper.name", paper).findAll().deleteAllFromRealm();
                                    list.remove(idx);
                                    adapter.notifyDataSetChanged();
                                }
                            });

                        }
                    })
                    .show();
        }
    };

    private View.OnClickListener listener_overview = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplication(), PaperViewActivity.class);
            intent.putExtra("paper", list.get((int) v.getTag()));
            startActivity(intent);
        }
    };

    // end
}
